package com.ai.module.chat.config.advice;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.core.io.Resource;
import com.ai.common.BaseResp;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestControllerAdvice(basePackages = {"com.ai.mj.controller", "com.**.controller"}, annotations = {RestController.class})
public class GptResponseAdvice implements ResponseBodyAdvice<Object> {

    private final ObjectMapper objectMapper;

    public GptResponseAdvice(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof BaseResp) {
            return body;
        }

        try {
            if (body instanceof String) {
                // 处理字符串类型的返回
                return objectMapper.writeValueAsString(BaseResp.success(body));
            }
            if (body==null){
                return  BaseResp.success(null);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return BaseResp.fail(ex.getMessage());
        }

        if (body instanceof InputStream || body instanceof Resource) {
            // 对文件和流直接返回，不封装
            return body;
        }
        if (body instanceof Map){
            HashMap<String, Object> errorMap = (HashMap<String, Object>) body;
            Object status = errorMap.get("status");
            Object error = errorMap.get("error");
            if (Objects.nonNull(error)
            && Objects.nonNull(status)){
               return BaseResp.fail(body,Integer.parseInt(status+""));
            }
        }

        return BaseResp.success(body);
    }

}
